#include "framechoose.h"
#include "ui_framechoose.h"
#include "dbconnection.h"

FrameChoose::FrameChoose(QWidget *parent) :
    QFrame(parent),
    ui(new Ui::FrameChoose)
{
    ui->setupUi(this);
    connect(ui->btnAdd, SIGNAL(clicked()), this, SLOT(select()));
    connect(ui->btnClear, SIGNAL(clicked()), this, SLOT(clear()));
    lc = new ListChoose();
    lc->setWindowTitle("Выберите значение");
    lc->setWindowModality(Qt::ApplicationModal);
    connect(lc, SIGNAL(accepted()), this, SLOT(getDataFromList()));
}

FrameChoose::~FrameChoose()
{
    delete ui;
}

void FrameChoose::clear()
{
    ui->label->clear();
    mcurrentID = "";
}

void FrameChoose::select()
{   
    lc->show();
}

void FrameChoose::setReadOnly(const bool &b)
{
    ui->btnAdd->setEnabled(!b);
    ui->btnClear->setEnabled(!b);
}

void FrameChoose::setTable(const QString theTableName)
{
    mtable = theTableName;
    lc->loadData(mtable, "");
    //вытаскиваем показываемое поле
    QString sql = "select * from apdmclass "
                  "where classname='%1'";
    QSqlQuery query(dbconnection::instance()->database());
    query.prepare(sql.arg(mtable));
    QString namefld = "";
    if(query.exec())
    {
        if(query.next())
            namefld = query.value(query.record().indexOf("replacefield")).toString();
    }
    else QMessageBox::information(0, "error at select fldname", query.lastError().text());
    sql = "select * from %1";
    query.prepare(sql.arg(theTableName));

    if(query.exec())
    {
        QSqlRecord rec = query.record();
        while(query.next())
        {
            eventidname.insert(QUuid(query.value(rec.indexOf("eventid")).toString()),
                               query.value(rec.indexOf(namefld)).toString());
        }
    }
    else QMessageBox::information(0, "error at select data", query.lastError().text());

}

void FrameChoose::getDataFromList()
{
    mcurrentID = QUuid(lc->selectedID());
    ui->label->setText(eventidname[mcurrentID]);
}

void FrameChoose::setID(const QUuid theID)
{
    mcurrentID = theID;
    ui->label->setText(eventidname[mcurrentID]);
    //QMessageBox::information(0, "set id", theID+' '+eventidname[theID]);
}
